#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : data_format.py
@Author  : different && 道阻且长,行则将至 行而不辍,未来可期
@Time    : 2021/10/30 09:38
@Desc    :

"""
import logging
import re


# 公共方法
def ret_max(a, b, is_sql=False):
    if is_number(a):
        try:
            if float(a) > float(b):
                a, b = b, a
            return a, b
        except Exception as e:
            logging.warning(e)
        try:
            if float(a) > float(b):
                a, b = b, a
            return a, b
        except Exception as e:
            logging.warning(e)
        return a, b
    if is_sql:
        a = '\'' + a + '\''
        b = '\'' + b + '\''
        return a, b
    return a, b


def ret_arr(val: list):
    """
    给字符串加上''
    """
    arr = []
    for i in val:
        if is_number(i):
            arr.append(i)
        else:
            i = '\'' + i + '\''
            arr.append(i)
    return arr


def ret_attr_sql(title, val: list):
    """
    多属性分组
    """
    param = []
    for i in val:
        param.append(f"""attr -> '$."{title}"' = {i}""")
    return " OR ".join(param)


def attr_format(value):
    if isinstance(value, str):
        value = value.split(',')
    res = []
    for i in value:
        attr = i.split('-')
        if len(attr) == 1:
            res.append({'lower_bound': attr[0], 'upper_bound': attr[0]})
        elif len(attr) == 2:
            res.append({'lower_bound': attr[0], 'upper_bound': attr[1]})
        else:
            print('分组错误')
            raise
    return res


def group_data_format(value, status=False):
    if isinstance(value, list):
        a, b = value[0], value[1]
        if a == b and status:
            return a
        if a != b:
            a, b = ret_max(a, b)
            return '-'.join([a, b])
    if isinstance(value, str):
        data = value.split('-')
        if len(data) == 1:
            return data[0], data[0]
        if len(data) == 2:
            return data[0], data[1]


def is_number(num):
    pattern = re.compile(r'^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$')
    result = pattern.match(num)
    if result:
        return True
    return False
